<template>
	<div class="container">
		<h1 style="text-align: center;font-weight: bold;">{{ id ? '修改' : '创建' }}总控材料计划</h1>
		<a-form ref="formRef" :model="formState" layout="vertical" @finish="savePlan">
			<a-row :gutter="20">
				<a-col :span="24">
					<h3>计划信息</h3>
				</a-col>
				<a-col :span="12">
					<a-form-item label="选择项目" name="project_id" :rules="{ required: true, message: '请选择项目' }">
						<a-select v-model:value="formState.project_id" :disabled="route.query.parent_id > 0" :show-search="true" placeholder="请选择项目" :options="projectOptions" option-filter-prop="label" @change="changeProject"></a-select>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="计划名称" name="name" :rules="{ required: true, message: '请输入计划名称' }">
						<a-input v-model:value="formState.name" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="计划编号" name="code" :rules="{ required: true, message: '请输入计划编号' }">
						<a-input v-model:value="formState.code" />
					</a-form-item>
				</a-col>

				<a-col :span="12">
					<a-form-item label="附件" name="file_path">
						<a-upload v-model:file-list="formState.file_path" name="upload" :action="`${baseURL}/contract/upload`" :show-upload-list="true" :headers="{ Authorization: `Bearer ${proxy.$cookies.get('token')}` }" :before-upload="beforeUpload" @change="changeUpload">
							<a-button>
								<template v-if="uploading">
									<loading-outlined />上传中...
								</template>
								<template v-else>
									<import-outlined />上传附件
								</template>
							</a-button>
						</a-upload>
					</a-form-item>
				</a-col>
				<!--
				<a-col :span="12">
					<a-form-item label="计划制定人" name="user_ids" :rules="{required:true, message:'请选择计划制定人'}">
						<a-select v-model:value="formState.user_ids" show-search="true" mode="multiple" placeholder="请选择计划制定人" :options="userOptions" option-filter-prop="label"></a-select>
					</a-form-item>
				</a-col>
				
				<a-col :span="12">
					<a-form-item label="计划日期" name="plan_date" :rules="{required:true, message:'请选择计划日期'}">
						<a-date-picker v-model:value="formState.plan_date" style="width:100%" />
					</a-form-item>
				</a-col>-->

				<a-col v-if="route.query.parent_id > 0" :span="24">
					<h1 style="text-align: center;font-weight: bold;">物资计划清单</h1>

					<div class="table-toolbar mb-3">
						<a-space>
							<a-button type="primary" @click="addMaterialModel(1)">
								<plus-outlined />新增
							</a-button>
							<!--
							<a-button v-if="route.query.parent_id" class="cache-btn" @click="handleCache">
								<DeliveredProcedureOutlined />暂存
							</a-button>
							-->
							<a-space>
								<a-select v-model:value="formState.num" placeholder="请选择条数" :options="numOptions" option-filter-prop="label" @change="addMaterialModel"></a-select>条
							</a-space>
						</a-space>
					</div>
					<a-table :data-source="formState.materials" :scroll="tableScroll" :columns="planMaterialColumns" :row-key="(record) => record.key" :pagination="false">
						<template #bodyCell="{ column, record, index }">
							<template v-if="column.dataIndex === 'name'">
								<a-form-item :name="['materials', index, 'source_id']" :rules="{ required: true, message: '请选择材料名称' }">
									<a-tree-select v-model:value="formState.materials[record.key].source_id" :dropdown-match-select-width="false" :show-search="true" placeholder="请选择材料名称" allow-clear :tree-data="materialOptions" tree-node-filter-prop="label" style="width:100%" @change="(id) => changeMaterial(id, record)">
										<template #title="{ label }">{{ label }}</template>
									</a-tree-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'model'">
								<a-form-item :name="['materials', index, 'id']" :rules="{ required: true, message: '请选择规格' }">
									<!--
									<a-spin :spinning="formState.materials[record.key].source_id > 0 && !materialModelOptions[record.source_id]?.length">
									-->
									<a-spin :spinning="formState.materials[record.key].source_id > 0 && record.loading">
										<a-select v-model:value="formState.materials[record.key].id" :show-search="true" option-filter-prop="model" placeholder="请选择" :options="materialModelOptions[record.source_id] || []" allow-clear :field-names="{ value: 'id', label: 'model' }" style="width:100%" @change="(v) => changeMaterialModel(record.key, materialModelOptions[record.source_id], v)"></a-select>
									</a-spin>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'unit'">
								<!--
								<a-form-item :name="['materials', index, 'unit']" :rules="{ required: true, message: '请选择计量单位' }">
									<a-select v-model:value="formState.materials[record.key].unit" :show-search="true" placeholder="请选择" :options="unitOptions" :field-names="{ value: 'name' }" style="width:100%"></a-select>
								</a-form-item>
								-->
								{{ formState.materials[record.key].unit || '-' }}
							</template>
							<template v-else-if="column.dataIndex === 'quantity'">
								<a-form-item :name="['materials', index, 'quantity']" :rules="{ required: true, message: '请输入数量' }">
									<a-input-number v-model:value="formState.materials[index]['quantity']" disabled />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'gonghao'">
								<a-form-item :name="['materials', index, 'gonghao_' + column.extra]">
									<a-input-number v-model:value="formState.materials[index]['gonghao_' + column.extra]" placeholder="请输入数量" @change="setQty(record, index)" />
								</a-form-item>
							</template>

							<template v-else-if="column.key === 'operation'">
								<a-space>
									<a-button type="link" @click="copyMaterialModel(record)">
										<copy-outlined />复制
									</a-button>

									<a-popconfirm title="确定要删除当前材料吗？" ok-text="是" cancel-text="否" @confirm="deleteMaterialModel(record.key)">
										<a-button type="link" style="color:#ff7875">
											<delete-outlined />删除
										</a-button>
									</a-popconfirm>
								</a-space>
							</template>
						</template>
					</a-table>
				</a-col>

				<!-- <a-col v-if="route.params.id && route.query.parent_id>0" :span="24">
					<h1 style="text-align: center;font-weight: bold;">原物资计划清单</h1>
					<a-table :data-source="oldMaterials" :scroll="tableScroll" :columns="MaterialColumns" :row-key="(record) => record.key"></a-table>
				</a-col>-->

				<a-col :span="24">
					<a-form-item label="备注" name="memo">
						<a-textarea v-model:value="formState.memo" :auto-size="{ minRows: 4, maxRows: 6 }"></a-textarea>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="20">
				<a-col :span="24" class="py-4 text-center">
					<a-space>
						<!--
						<a-button v-if="route.query.parent_id" class="cache-btn" @click="handleCache">
							<DeliveredProcedureOutlined />暂存
						</a-button>
						-->
						<a-button v-if="!formState.parent_id || (formState.parent_id && ![0, 1, 2].includes(formState.workflow_status))" type="primary" html-type="submit">
							<save-outlined />保存
						</a-button>
						<a-workflow v-if="formState.id && formState.parent_id" v-model:status="formState.workflow_status" module="plan" :target-id="formState.id" :project-id="formState.project_id" :code="formState.code" :user-id="formState.opr_id" @submit="submitPurchase"></a-workflow>
						<a-button @click="closeTab('/plan')">
							<close-outlined />关闭
						</a-button>
					</a-space>
				</a-col>
			</a-row>
		</a-form>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance, inject, toRaw } from "vue";
import { PlusOutlined, DeliveredProcedureOutlined, DeleteOutlined, SaveOutlined, CopyOutlined, CloseOutlined } from "@ant-design/icons-vue";
import dayjs from "dayjs";
import { baseURL } from "../utils/request";

import { post, listToTree } from "../utils";

import { useRoute, useRouter } from "vue-router";
import { AWorkflow } from "@/components/index.js";

//缓存数据
const handleCache = () => {
	// console.log(formState.value);
	proxy.$message.success("缓存成功");
	localStorage.setItem("plan-save", JSON.stringify(formState.value));
};

const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 680 }));
const route = useRoute();
// console.log(route)
const currentQuery = route.query;
const router = useRouter();
const id = computed(() => {
	return route.params.id || 0;
});

const formState = ref({ parent_id: route.query.parent_id || 0, materials: [] });
const projectOptions = ref([]);
const userOptions = ref([]);
const oldMaterials = ref([]);
onMounted(() => {
	const { parent_id } = formState.value;
	//从缓存中取出数据填充form
	if (route.query.parent_id) {
		//这个判断的目的是应为复用了组件,子级页面要缓存 这个页面不缓存,子级页面路径参数有parent_id
		/*
		const cacheData = localStorage.getItem("plan-save");
		formState.value = JSON.parse(cacheData) || formState.value;
		*/
	}

	if (parent_id) {
		if (id.value) {
			// 编辑子计划
			post("plan/info", { id: id.value }).then(async data => {
				data.materials = data.materials.map((d, i) => {
					d.key = i;

					const { unit, quantity } = d.PlanMaterial;
					d.unit = unit;
					d.quantity = quantity;

					//d.loading = false;
					return d;
				});
				//构建工号
				post("department/info", { id: data.project_id }).then(d => {
					//获取工号
					pointData.value = d.pointData;
				});
				//获取所有规格
				if (data.materials.length) {
					const sourceId = [];
					data.materials.forEach(item => {
						sourceId.push(item.id);
						sourceId.push(item.source_id);
					});

					await post("material", { source_id: sourceId.join(","), page_size: Infinity, attributes: "id,attr,model,source_id,unit", status: 1 }).then(({ data }) => {
						materialModelOptions.value = (() => {
							const array = [];
							data.forEach(d => {
								if (!array[d.source_id]) array[d.source_id] = [];
								if (d.attr) d.model = `${d.model}（${d.attr}）`;
								array[d.source_id].push(d);
							});

							return array;
						})(data);
					});

					data.materials.map(d => {
						if (materialModelOptions.value[d.source_id]?.length > 0) d.loading = false;
					});
				}

				formState.value = data;
				formState.value.file_path = JSON.parse(formState.value.file_path || "[]");
			});
			// //原计划物资清单
			// post("plan/hebing", { id: id.value }).then(data => {
			// 	oldMaterials.value = data.map((d, i) => {
			// 		d.key = i;
			// 		return d;
			// 	});
			// });
		} else {
			// 创建子计划
			post("plan/info", { id: parent_id }).then(data => {
				const { code, project_id, children } = data;
				formState.value = {
					...formState.value,
					name: `总控计划${children.length + 1}`,
					code: code + `-${children.length + 1}`,
					project_id
				};

				//构建工号
				post("department/info", { id: data.project_id }).then(d => {
					//获取工号
					pointData.value = d.pointData;
				});
			});
		}
	} else if (id.value) {
		// 编辑主计划
		post("plan/info", { id: id.value }).then(data => {
			//构建工号
			post("department/info", { id: data.project_id }).then(d => {
				//获取工号
				pointData.value = d.pointData;
			});
			formState.value = data;
		});
	}

	post("user").then(({ data }) => {
		userOptions.value = data.map(d => {
			return {
				value: d.id,
				label: d.fullname || d.username
			};
		});
	});
	//projectOptions
	post("department/projects?type=3", { page_size: 1000 }).then(({ data }) => {
		projectOptions.value = data.map(d => {
			return {
				value: d.id,
				label: d.name
			};
		});
	});
});
const pointData = ref([]);
const hasPoint = ref(true);
const changeProject = value => {
	const project_id = value;
	post("department/info", { id: project_id }).then(data => {
		//自动生成计划编码
		if (data.name) {
			let py_name = "";
			const name = data.company_name + "-" + data.name;
			post("util/pinyin", { value: name }).then(res => {
				res.value.forEach(d => {
					py_name += d.toUpperCase();
				});
				//获取计划最大ID
				let maxid = 0;
				post("plan/maxid", { project_id: project_id }).then(max => {
					if (!parseInt(max)) {
						maxid = 1;
					} else {
						maxid = parseInt(max) + 1;
					}
					//formState.value.code = "ZTJGSJ-" + py_name + "-" + parseInt(maxid);
					formState.value.code = "ZTJGSJ-" + py_name;
				});
			});
		}
		//获取工号
		pointData.value = data.pointData;
		if (data.pointData.length === 0) {
			hasPoint.value = false;
			proxy.$message.error("只能选择有工号的项目");
		} else {
			hasPoint.value = true;
		}
	});
};
const setQty = (item, index) => {
	const material = toRaw(formState.value.materials[index]);
	const quantity = pointData.value.reduce((total, curr) => {
		total += Number.parseFloat(material["gonghao_" + curr.id] || 0);
		return total;
	}, 0);
	formState.value.materials[index].quantity = quantity;
	// formState.value.materials.forEach(d => {
	// 	let quantity = 0;
	// 	pointData.value.forEach(p => {
	// 		if (Number.parseFloat(d["gonghao_" + p.id]) >= 0) {
	// 			quantity = Number.parseFloat(quantity) + Number.parseFloat(d["gonghao_" + p.id]);
	// 			quantity = quantity.toFixed(2);
	// 		}
	// 	});
	// 	d.quantity = quantity;
	// });
};
const { proxy } = getCurrentInstance();
const formRef = ref();
const savePlan = () => {
	//总数量检测
	let qty_error = 0;
	formState.value.materials.forEach(d => {
		if (parseFloat(d.quantity) === parseFloat(0)) {
			qty_error = 1;
		}
	});
	if (qty_error === 1) {
		proxy.$message.error("请填写计划数量");
		return;
	}

	if (hasPoint.value === false) {
		proxy.$message.error("请选择有工号的项目");
		return;
	}
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();
			const params = { ...formState.value };
			// 子计划
			if (route.query.parent_id > 0) {
				if (!params.materials.length) {
					proxy.$message.error("请添加材料清单");
					return;
				}
				params.materials = JSON.stringify(
					params.materials.map(({ id, unit, quantity, standard, add_time, use_time, useto, time_unit, memo, ...args }) => {
						const data = {};
						for (const key in args) {
							if (key.indexOf("gonghao_") > -1) {
								data[key] = args[key];
							}
						}
						return {
							id,
							unit,
							quantity,
							standard,
							add_time,
							use_time,
							useto,
							time_unit,
							memo,
							...data
						};
					})
				);
			}

			// const { plan_date, user_ids = [] } = params;
			// if (plan_date) params.plan_date = dayjs(plan_date).format("YYYY-MM-DD");
			// params.user_ids = user_ids.join(",");
			params.type = 1;
			// 一级总控新增
			if (!params.parent_id && !params.id) {
				params.workflow_status = 2;
			}
			if (params.file_path) params.file_path = JSON.stringify(params.file_path);

			const { id, project_id, name, code, file_path, materials, type, workflow_status, parent_id, memo } = params;
			post("plan/save", {
				id,
				project_id,
				name,
				code,
				file_path,
				materials,
				type,
				workflow_status,
				parent_id,
				memo
			})
				.then(({ id }) => {
					proxy.$message.success("信息提交成功", 1);
					if (route.query.parent_id) {
						// 提交子计划
						router.push(`/plan/edit/${id}?parent_id=${route.query.parent_id}`);
					} else {
						router.push("/plan/edit/");
					}
					//清除缓存
					//localStorage.removeItem("plan-save");
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		})
		.catch(err => {});
};
const planMaterialColumns = computed(() => {
	const planMaterialColumns = [
		{
			title: "ID",
			dataIndex: "key",
			width: 60,
			align: "center",
			extra: 0,
			customRender: ({ text, record, index, column }) => {
				return text + 1;
			}
		},
		{
			title: "材料名称",
			dataIndex: "name",
			width: 150,
			extra: 0
		},
		{
			title: "材料规格",
			dataIndex: "model",
			width: 150,
			extra: 0
		},
		{
			title: "单位",
			dataIndex: "unit",
			width: 150,
			extra: 0,
			align: "center"
		}
	];
	pointData.value.forEach((p, i) => {
		planMaterialColumns.push({
			title: p.name,
			dataIndex: "gonghao",
			extra: p.id,
			align: "center",
			width: 120
		});
	});
	planMaterialColumns.push(
		{
			title: "总数",
			dataIndex: "quantity",
			width: 120,
			extra: 0,
			align: "center"
		},
		{
			title: "操作",
			key: "operation",
			sorter: false,
			fixed: "right",
			width: 160,
			align: "center"
		}
	);
	return planMaterialColumns;
});

const MaterialColumns = computed(() => {
	const MaterialColumns = [
		{
			title: "ID",
			dataIndex: "key",
			width: 60,
			align: "center",
			extra: 0,
			customRender: ({ text, record, index, column }) => {
				return text + 1;
			}
		},
		{
			title: "材料名称",
			dataIndex: "name",
			width: 150,
			extra: 0
		},
		{
			title: "材料规格",
			dataIndex: "model",
			width: 150,
			extra: 0
		},
		{
			title: "单位",
			dataIndex: "unit",
			width: 150,
			extra: 0,
			align: "center"
		},
		{
			title: "数量",
			dataIndex: "quantity",
			width: 120,
			extra: 0,
			align: "center"
		}
	];
	pointData.value.forEach((p, i) => {
		MaterialColumns.push({
			title: p.name,
			dataIndex: "gonghao_" + p.id,
			extra: p.id,
			align: "center",
			width: 120
		});
	});

	return MaterialColumns;
});

const unitOptions = ref([]);
post("dictionary", { root_code: "MATERIAL_UNIT" }).then(data => {
	unitOptions.value = data;
});
const numOptions = [
	{
		value: 1,
		label: "1"
	},
	{
		value: 20,
		label: "20"
	},
	{
		value: 30,
		label: "30"
	},
	{
		value: 50,
		label: "50"
	}
];
const materialOptions = ref([]);

post("dictionary", { root_code: "MATERIAL_CATEGORY" }).then(data => {
	const { root_id: rootId } = data[0] || {};
	let materialTree = listToTree(data, rootId).filter(item => [2, 56, 57, 61].includes(item.id));

	materialTree = materialTree.filter(d => {
		d.children = d.children.filter(c => {
			//过滤机械设备里面的工程机械
			if (c.id === 672) {
				return false;
			}

			return true;
		});

		return true;
	});

	materialOptions.value = materialTree;
	//获取所有规格
	// post("material", { source_id: data.map(d => d.id).join(","), page_size: Infinity, attributes: 'id,attr,model,source_id,unit' }).then(({ data }) => {
	// 	materialModelOptions.value = (() => {
	// 		const array = [];
	// 		data.forEach(d => {
	// 			if (!array[d.source_id]) array[d.source_id] = [];
	//
	// 			if (d.attr) d.model = `${d.model}（${d.attr}）`;
	//
	// 			array[d.source_id].push(d);
	// 		});
	//
	// 		return array;
	// 	})(data);
	// });
});

const materialModelOptions = ref({});

const changeMaterial = (id, record) => {
	//强制选择规格
	record.id = null;
	record.loading = true;

	if (!id) return;

	post("material", { source_id: id, page_size: Infinity, attributes: "id,attr,model,source_id,unit", status: 1 }).then(({ data }) => {
		materialModelOptions.value[id] = data.map(d => {
			if (d.attr) d.model = `${d.model}（${d.attr}）`;

			return d;
		});

		record.loading = false;
	});
};

const addMaterialModel = value => {
	if (!value || value <= 0) {
		value = 1;
	}
	for (let i = 1; i <= value; i++) {
		formState.value.materials.push({ key: formState.value.materials.length });
	}
};

const copyMaterialModel = record => {
	formState.value.materials.push({ ...record, key: formState.value.materials.length });
};

const deleteMaterialModel = key => {
	const { materials } = formState.value;

	const index = materials.findIndex(d => d.key === key);
	if (index === false) return;
	materials.splice(index, 1);

	formState.value = {
		...formState.value,
		materials: materials.map((d, i) => {
			d.key = i;
			return d;
		})
	};
};

//调用父页面closeTab方法
/*
//父页面定义closeTab方法
provide("closeTab", path => {
	
});
*/
const closeTab = inject("closeTab");
const submitPurchase = () => {
	proxy.$message.success("总控计划提交成功", 1);
	closeTab("/plan");
};

const changeMaterialModel = (key, options, v) => {
	const { unit = "" } = options.find(d => d.id === v);
	formState.value.materials.find(d => d.key === key).unit = unit;
};

const uploading = ref(false);
//上传前校验
const beforeUpload = file => {
	uploading.value = true;
	if (file.type !== "application/pdf") {
		proxy.$message.error("只能上传PDF文件");
		uploading.value = false;

		return false;
	}
	const isLt10M = file.size / 1024 / 1024 < 10;
	if (!isLt10M) {
		proxy.$message.error("只能上传10MB以下文件");
		uploading.value = false;
		return false;
	}
};
// 上传并提交文件
const changeUpload = ({ file }) => {
	if (file.status === "done") {
		formState.value.file_path.push({
			name: file.name,
			url: file.response.data.url
		});
		formState.value.file_path = formState.value.file_path.filter(item => item.url);
		uploading.value = false;
		proxy.$message.success("上传成功");
	}
	if (!file.status) {
		formState.value.file_path = formState.value.file_path.filter(item => item.url);
	}
};
</script>

<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;

	h2 {
		font-size: 16px;
		font-weight: 600;
		line-height: 30px;
		margin-bottom: 20px;
	}

	h3 {
		line-height: 40px;
		font-size: 16px;
		font-weight: 400;
		margin-bottom: 20px;

		display: flex;
		align-items: center;

		&:before {
			content: "";
			display: block;
			width: 2px;
			height: 20px;
			background: rgb(24, 144, 255);
			margin-right: 10px;
		}
	}

	h4 {
		font-weight: 600;
		margin: 15px 0;
		line-height: 30px;
	}
}

:deep(.ant-table-cell) .ant-form-item {
	margin-bottom: 0;

	.ant-form-item-explain {
		position: absolute;
		bottom: -24px;
	}
}

:deep(.ant-input[disabled]) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}

:deep(.ant-input-disabled) {
	color: rgba(0, 0, 0, 0.65);
	background: #fff;
	border: 1px solid #d9d9d9;
}

.cache-btn {
	background-color: #0d9424;
	color: #fff;
}
</style>
